<?php
/**
 * Copyright (C), 2016-2022, Shall Buy Life info. Co., Ltd.
 * Filename:
 * Description:
 *
 * @author: lwl
 * @Create Date: 2022/5/19 3:24 PM
 * @Update Date: 2022/5/19 3:24 PM By lwl
 * @version: 版本号
 */

namespace Example\Models;

use Example\Constants\CodeMessageConstant;
use Illuminate\Database\Eloquent\Model;

class BasicModel extends Model
{

    public $_name = null;
    /**
     * FunctionName:basicQuery
     * Description:查询
     * Author: lwl
     * @param int $id id
     * @param array $where 条件 一维二维数组
     * @param array $fields 查询字段一维数组
     * @param array $withs 关联关系一维数组
     * @param string $resultType 查询方式 first get
     * @param string $orderBy 排序方式 asc desc
     * @param string $orderByField 排序字段 field
     * @return mixed
     */
    public  function basicQuery(int $id = 0, array $where = [], array $fields = [], array $withs = [], string $resultType = 'first', string $orderBy = 'asc', string $orderByField = 'id')
    {
        $instance = $this->_name;

        if (!empty($where)) {
            $instance = $instance->where($where);
        }

        if ($id !== 0) {
            $instance = $instance->where('id', $id);
        }

        if (!empty($withs)){
            $instance = $instance->with($withs);
        }

        if (!empty($fields)) {
            $instance = $instance->select($fields);
        }

        return $instance->orderBy($orderByField, $orderBy)->$resultType();
    }

    /**
     * FunctionName:basicDelete
     * Description:删除
     * Author: lwl
     * @param int $id id
     * @param array $where 条件 一维二维数组
     * @return bool
     */
    public function basicDelete(int $id = 0, array $where = []): bool
    {
        $instance = $this->_name;
        if (!empty($where)) {
            $instance = $instance->where($where);
        }

        if ($id !== 0) {
            $instance = $instance->where('id', $id);
        }

        if (!$result = $instance->first()) {
            fail(CodeMessageConstant::ERROR_DATA_NOT_EXISTS);
        }
        return $result->delete();
    }

    /**
     * FunctionName:basicEdit
     * Description:更新
     * Author: lwl
     * @param int $id id
     * @param array $where 条件 一维二维数组
     * @param $editParams 更新字段 一维数组
     * @return mixed
     */
    public function basicEdit(int $id = 0, array $where = [], $editParams = []):bool
    {
        $instance = $this->_name;
        if (!empty($where)) {
            $instance = $instance->where($where);
        }

        if ($id !== 0) {
            $instance = $instance->where('id', $id);
        }

        if (!$result = $instance->first()) {
            fail(CodeMessageConstant::ERROR_DATA_NOT_EXISTS);
        }
        return $result->update($editParams);
    }
}
